﻿using Cookbook.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Graphics.Printing;
using Windows.UI.Xaml.Printing;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Cookbook.Views
{
  /// <summary>
  /// An empty page that can be used on its own or navigated to within a Frame.
  /// </summary>
  public sealed partial class RecipeDetailView : Page
  {
    private RecipeDetailViewModel viewModel;
    //private PrintDocument document;

    public RecipeDetailView()
    {
      this.InitializeComponent();
    }

    protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
      base.OnNavigatedTo(e);

      var id = (int)e.Parameter;

      this.viewModel = new RecipeDetailViewModel();
      this.DataContext = this.viewModel;

      await this.viewModel.LoadRecipeDetail(id);

      InitializePrinting();
    }

    private IPrintDocumentSource documentSource;

    private void InitializePrinting()
    {
      var visual = new RecipeDetailPrintView(this.viewModel);

      var document = new PrintDocument();

      document.GetPreviewPage += (s, args) =>
      {
        document.SetPreviewPage(1, visual);
      };

      document.AddPages += (s, args) => 
      {
        document.AddPage(visual);
        document.AddPagesComplete();
      };

      documentSource = document.DocumentSource;

      var printManager = PrintManager.GetForCurrentView();
      printManager.PrintTaskRequested += printManager_PrintTaskRequested;
    }

    void printManager_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
    {
      args.Request.CreatePrintTask(this.viewModel.Recipe.Title, p => p.SetSource(documentSource));
    }
  }
}
